import 'dart:math' as math;
import 'package:flutter/material.dart';

// void main() => runApp(DemoPage());

class DemoPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Correctly Aligned Rotated Rectangles'),
        ),
        body: Center(
          child: CustomPaint(
            size: Size(300, 300),
            painter: CorrectlyAlignedVerticesPainter(),
          ),
        ),
      ),
    );
  }
}

class CorrectlyAlignedVerticesPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.blue
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;

    final center = Offset(size.width / 2, size.height / 2);
    final double width = 200;
    final double height = 100;
    final rotationAngle = math.pi / 4; // 45度角
    final double smallRectSide = 20.0; // 小矩形边长

    // 绘制大矩形
    Path bigRectPath = Path();
    bigRectPath.moveTo(-width / 2, -height / 2);
    bigRectPath.lineTo(width / 2, -height / 2);
    bigRectPath.lineTo(width / 2, height / 2);
    bigRectPath.lineTo(-width / 2, height / 2);
    bigRectPath.close();

    canvas.save();
    canvas.translate(center.dx, center.dy);
    canvas.rotate(rotationAngle);
    canvas.drawPath(bigRectPath, paint);

    List<Offset> bigRectVertices = [
      Offset(-width / 2, -height / 2),
      Offset(width / 2, -height / 2),
      Offset(width / 2, height / 2),
      Offset(-width / 2, height / 2),
    ];

    // 对于大矩形的每个顶点，绘制小矩形
    for (var vertex in bigRectVertices) {
      Path smallRectPath = Path();
      smallRectPath.moveTo(0, 0); // 小矩形的一个顶点与大矩形顶点重合
      smallRectPath.lineTo(smallRectSide * math.cos(rotationAngle),
          smallRectSide * math.sin(rotationAngle));
      smallRectPath.lineTo(
          smallRectSide * math.cos(rotationAngle) -
              smallRectSide * math.sin(rotationAngle),
          smallRectSide * math.sin(rotationAngle) +
              smallRectSide * math.cos(rotationAngle));
      smallRectPath.lineTo(-smallRectSide * math.sin(rotationAngle),
          smallRectSide * math.cos(rotationAngle));
      smallRectPath.close();

      canvas.save();
      canvas.translate(vertex.dx, vertex.dy); // 移动到大矩形的顶点
      canvas.drawPath(smallRectPath, paint); // 绘制小矩形
      canvas.restore();
    }
    canvas.restore();
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
